/**
 * 基础菜单 商品管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>模型实例列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="formInline.algorithmName" placeholder="模型实例名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table  :data="listData" highlight-current-row v-loading="loading"  element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="modelConfigName" label="模型实例名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="modelConfigDesc" label="模型实例简介" width="150">
      </el-table-column>
      <el-table-column sortable prop="config" label="算法执行配置" width="200" v-if="false">
      </el-table-column>

      <el-table-column sortable prop="createTime" label="创建时间" width="200">
      </el-table-column>

      <el-table-column sortable prop="updateTime" label="修改时间" width="200">
      </el-table-column>

      <el-table-column sortable prop="epochs" label="epochs" width="100" v-if="false">
      </el-table-column>

      <el-table-column sortable prop="lr" label="lr" width="100" v-if="false">
      </el-table-column>

      <el-table-column sortable prop="batchSize" label="batchSize" width="100" v-if="false">
      </el-table-column>

      <el-table-column prop="actionStatus" label="训练状态">
        <template slot-scope="scope">
          <span v-if="scope.row.actionStatus === 'success'">训练成功</span>
          <span v-else-if="scope.row.actionStatus === 'error'">训练失败</span>
          <span v-else-if="scope.row.actionStatus === 'action'">正在训练</span>
          <span v-else>未训练</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看/编辑配置详情</el-button>
          <el-button size="mini" @click="handleAction(scope.$index, scope.row)">立即训练</el-button>
          <el-button size="mini" @click="handleDetail(scope.$index, scope.row)">查看训练详情</el-button>
          <el-button size="mini" @click="handleStop(scope.$index, scope.row)">停止训练</el-button>
          <el-button size="mini" v-show="scope.row.actionStatus === 'success'" @click="handleModelTest(scope.$index, scope.row)">模型测试</el-button>
          <el-button size="mini" v-show="scope.row.actionStatus === 'success'" @click="handlePred(scope.$index, scope.row)">模型部署</el-button>
          <el-button size="mini" type="danger" @click="deleteConfig(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination v-bind:childMsg="pageparm" @callFather="callFather"></Pagination>

    <!-- 添加界面 -->
    <el-dialog title="添加" :visible.sync="addFormVisible" width="80%" top="3%">
      <antv ref="antv" @jsonData="jsonData"></antv> 
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm1">保存</el-button>
      </div>
    </el-dialog>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="算法配置名称" prop="modelConfigName">
          <el-input size="small" v-model="editForm.modelConfigName" auto-complete="off" placeholder="请输入算法配置名称"></el-input>
        </el-form-item>
        <el-form-item label="算法配置简介" prop="modelConfigDesc">
          <el-input size="small" v-model="editForm.modelConfigDesc" auto-complete="off" placeholder="请输入算法配置简介"></el-input>
        </el-form-item>
        <el-form-item label="算法执行配置" prop="config">
          <el-input size="small" v-model="editForm.config" auto-complete="off" placeholder="请输入算法执行配置" disabled></el-input>
        </el-form-item>

        <el-form-item label="epochs" prop="epochs">
          <el-input size="small" v-model="editForm.epochs" auto-complete="off" placeholder="epochs"></el-input>
        </el-form-item>
        <el-form-item label="lr" prop="lr" >
          <el-input size="small" v-model="editForm.lr" auto-complete="off" placeholder="lr"></el-input>
        </el-form-item>
        <el-form-item label="batchSize" prop="batchSize">
          <el-input size="small" v-model="editForm.batchSize" auto-complete="off" placeholder="batchSize"></el-input>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm2">保存</el-button>
      </div>
    </el-dialog>

    <!-- 执行详情界面 -->
    <el-dialog :title="title" :visible.sync="detailFormVisible" width="40%" @click="closeDialog">
    <div class="pre">
      {{actionDetail }}
    </div>            

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" >取消</el-button>
        <el-button size="small" type="primary"  class="title" @click="closeDialog" >确定</el-button>
      </div>
    </el-dialog>

    <!-- 模型预测界面 可删除-->
    <el-dialog :title="title" :visible.sync="predictionFormVisible" width="80%" @click="closeDialog">
      <!-- 展示可用数据集 -->

    <!--预测数据集列表-->
    <el-table size="small" :data="predData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
      style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="dataName" label="预测数据集名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="dataDesc" label="数据集描述" width="150">
      </el-table-column>
      <el-table-column sortable prop="dataDesc" label="状态 1-训练数据集  2-预测数据集 -> 3-预测是否完毕" width="150">
      </el-table-column>
      <!-- <el-table-column sortable prop="xxx" label="数据集描述" width="150"> -->
      <!-- </el-table-column> -->
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">预测</el-button>
          <el-button size="mini"  @click="handleEdit(scope.$index, scope.row)">查看预测结果</el-button>
          <el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">下载预测结果</el-button>
        </template>
      </el-table-column>
    </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" >取消</el-button>
        <el-button size="small" type="primary"  class="title" @click="handleConfirm" >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {configList ,configSave ,configDelete ,configUpdate ,configAction ,detailList,modelStop,ModelDataListByModelId,getTagIdByModelId,actionStatus } from '../../api/userMG'
import Pagination from '../../components/Pagination'
import antv from '@/components/flower/antv'
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      addFormVisible: false, //控制新增页面显示与隐藏
      editFormVisible: false, //控制编辑页面显示与隐藏
      predictionFormVisible: false, //控制预测页面显示与隐藏
      detailFormVisible: false, //控制执行详情页面显示与隐藏
      title: '添加',
      actionDetail:'',
      editForm: {
        modelConfigName: '',
        modelConfigDesc: '',
        config:'',
        id:'',
        epochs:'',
        lr:'',
        batchSize:'',
      },
  
      
      // rules表单验证
      rules: {
        modelConfigName: [
          { required: true, message: '请输入算法名称', trigger: 'blur' }
        ],
        modelConfigDesc: [
          { required: true, message: '请输入算法配置简介', trigger: 'blur' }
        ],
        epochs: [
          { required: true, message: '请输入epochs', trigger: 'blur' }
        ],
        lr: [
          { required: true, message: '请输入lr', trigger: 'blur' }
        ],
        batchSize: [
          { required: true, message: '请输入batchSize', trigger: 'blur' }
        ],
      },
      formInline: {
        pageNum: 1,
        pageSize: 10,
        modelConfigName:''
      },
      // 删除部门
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //算法配置数据
      predData:[], //模型预测数据
      detailData:[
      // {
      //   text:'张三非法占有为目的，犯盗窃罪',
      //   result:'诈骗罪'
      // },
      // {
      //   text:'张三法外狂徒，入狱罪名放火',
      //   result:'放火罪'
      // }
    ],        //执行详情数据
    // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination,
    antv
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    
    handleModelTest: function (index, row) {
      if(row.actionStatus === 'success'){
        // 在导航时传递参数
        this.$router.push({ 
        path: '/algorithm/ModelTest', 
        query: { 
            data: row, 
            fromRoute:this.$route.path
        } 
        });
      }else{
        this.$message({
            type: 'info',
            message: '模型尚未训练完毕'
          })
      }

    },




    // 立即执行二次封装
    actionNow(row){
      configAction(row)
              .then(res => {
                if (res.code===0) {
                  if(res.data.actionStatus === 'success'){
                    this.$message({
                    type: 'success',
                    message: '算法配置\t'+row.modelConfigName + '\t执行成功!'
                  })
                  this.getdata(this.formInline)
                  }
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.loading = false
                this.$message.error('算法执行失败，请稍后再试！')
              })
    },
    //流程图保存回调
    jsonData(val) {
     
      val.config = JSON.stringify(val.data)
      val.createTime = new Date().toLocaleString().replace(/\//g, '-');
      val.updateTime = new Date().toLocaleString().replace(/\//g, '-');
      console.log(val)
      // graph.read(val.savedData);
      configSave(val).then(res =>{
      if(res.code !== 0){
          this.$message({
              type: 'info',
              message: res.msg
            })
        }else{
          this.$message({
              type: 'success',
              message: '新增算法配置成功！'
            })
          this.getdata(this.formInline)
        }
      }).catch(err => {
        this.$message.error('新增算法配置失败，请稍后再试！')
      })
      
      this.addFormVisible = false
  

    },
    // 获取算法配置列表
    getdata(parameter) {
      this.loading = true
      configList(parameter)
        .then(res => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data.rows
            // 分页赋值
            this.pageparm.currentPage = this.formInline.pageNum
            this.pageparm.pageSize = this.formInline.pageSize
            this.pageparm.total = res.data.records
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.pageNum = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.formInline.modelConfigName = typeof(this.formInline.algorithmName)==='undefined'?'':this.formInline.algorithmName
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.formInline.modelConfigName =typeof(this.formInline.algorithmName)==='undefined'?'':this.formInline.algorithmName
      this.getdata(this.formInline)
    },
    //添加算法配置
    handleAdd() {
      this.addFormVisible = true
    },

    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      this.title = '修改'
      this.editForm.modelConfigName=row.modelConfigName
      this.editForm.modelConfigDesc = row.modelConfigDesc
      this.editForm.config = row.config
      this.editForm.id = row.id
      this.editForm.epochs = row.epochs
      this.editForm.lr = row.lr
      this.editForm.batchSize = row.batchSize
    },

    //显示执行详情界面
    handleDetail: function (index, row) {
      this.title = row.modelConfigName +'\t执行详情'
      actionStatus(row.id)
        .then(res => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            if(res.data.actionStatus === null || res.data.actionStatus === ''){
              // this.detailData = []
              this.$message({
              type: 'info',
              message: '算法配置\t'+row.modelConfigName + '\t尚未执行!',
            })
            row.actionStatus = null
              
            }
            else if(res.data.actionStatus === 'action'){
              this.$message({
              type: 'info',
              message: '算法配置\t'+row.modelConfigName + '\t正在执行!', 
            })
            row.actionStatus = 'action'
            }
            else if(res.data.actionStatus === 'success'){
              // 执行成功 查询结果
              detailList(res.data.id).then(res=>{
                this.actionDetail = res.data.modelResult
                this.detailFormVisible = true
              }).catch(err=>{
                this.$message({
                type: 'error',
                message: err, 
            })
              })
              row.actionStatus = 'success'
            }else{
              this.$message({
              type: 'error',
              message: '算法配置\t'+row.modelConfigName + '\t执行错误!', 
            })
              row.actionStatus= 'error'
            }
          }
        })
        .catch(err => {
          alert(err)
          this.loading = false
          this.$message.error('执行详情加载失败，请稍后再试！')
        })
    },
    // 增加页面保存方法
    submitForm1() {
      this.$refs.antv.handlerSend()
    },
    // 编辑页面保存方法
    submitForm2() {
      this.editForm.updateTime = new Date().toLocaleString().replace(/\//g, '-');

      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交操作
          configUpdate(this.editForm).then(res =>{
            if(res.code !== 0){
              this.$message({
                  type: 'info',
                  message: res.msg
                })
            }else{
              this.$message({
                  type: 'success',
                  message: '修改算法配置成功！'
                })
              this.getdata(this.formInline)
            }
          }).catch(err => {
            this.$message.error('修改算法配置失败，请稍后再试！')
          })
          this.editFormVisible = false
        } else {
          // 校验不通过，阻止提交
          this.$message({
                  type: 'error',
                  message: '校验不通过，阻止提交'
                })
        }
      });


    },
    // 删除算法配置
    deleteConfig(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        configDelete(row.id)
          .then(res => {
            if (res.code===0) {
              this.$message({
                type: 'success',
                message: '算法配置已删除!'
              })

              this.getdata(this.formInline)
            } else {
              this.$message({
                type: 'info',
                message: res.msg
              })
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error('算法配置删除失败，请稍后再试！')
          })
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 立即执行
    handleAction(index, row) {
      actionStatus(row.id)
        .then(res => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            // 算法尚未执行，立即执行
            if(res.data.actionStatus === '' || res.data.actionStatus ===null){
              this.actionNow(row)
              row.actionStatus = 'action'
            // 算法正在执行
            }else if(res.data.actionStatus === 'action'){
              this.$message({
              type: 'info',
              message: '算法正在执行，请稍后再试',
            })}
            // 算法执行成功
            else if(res.data.actionStatus === 'success'){
              this.$confirm('确定要重新执行吗?', '算法执行成功', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'success'
            }).then(() => {
              this.actionNow(row);
              row.actionStatus = 'action'
            })
          }
            // 算法执行错误
            else{
              this.$confirm('确定要重新执行吗?', '算法执行错误', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            }).then(() => {
              this.actionNow(row);
              row.actionStatus = 'action'
            })
            }
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err + '算法执行错误，请稍后再试！')
        })
    },
    handleStop(index, row){
      modelStop(row.id)
        .then(res => {
          this.loading = false
          if (res.code !== 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.$message({
              type: 'success',
              message: '算法停止成功',
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err + '算法执行错误，请稍后再试！')
        })
    },
    handlePred(index, row){
      if(row.actionStatus === 'success'){
        this.$message({
              type: 'info',
              message: 'test',
            })
        // this.predictionFormVisible = true
        // this.title = '模型预测'
          // const jsonData = '[{"modelId":7,"sort":1},{"dataId":15,"sort":2}]';
          // const parsedData = JSON.parse(row.config);

          // 获取数组中的第一个对象的 modelId 值
          // const modelId = parsedData[0].modelId;
          // ModelDataListByModelId(modelId)
          // .then(res =>{
            // this.predData = res.data
          // })
          // .catch(err =>{

          // })
      }

    },
    handleConfirm() {
      // console.log('选中的行数据：', this.selectedRows);

      // this.$router.push({ 
      //   path: '/algorithm/Prediction', 
      //   query: { 
      //       data: this.selectedRows, 
      //       fromRoute:this.$route.path
      //   } 
      //   });
      // 在这里可以对选中的行数据进行进一步处理
      this.closeDialog(); // 关闭对话框
    },



    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.addFormVisible = false
      this.editFormVisible = false
      this.detailFormVisible = false
      this.predictionFormVisible = false
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
.pre {
        white-space: pre-wrap;
        text-align: center;
    }
</style>

 
 